package com.jiang.booksystem.manager;

import com.jiang.booksystem.dao.entity.Book;
import com.jiang.booksystem.dao.entity.UserBookBorrow;
import com.jiang.booksystem.dao.entity.dos.BookAggre;
import com.jiang.booksystem.dao.mapper.BookMapper;
import com.jiang.booksystem.dao.mapper.UserBookBorrowMapper;
import com.jiang.booksystem.exception.ServiceException;
import com.jiang.booksystem.utils.AssertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 业务逻辑类
 */
@Service
public class BookManager {

    @Autowired
    private BookMapper mapper;



    public List<BookAggre> search(Integer borrowUserId) {

            return mapper.search(borrowUserId);

    }



    public void add(Book book) throws Exception {
        // 检验参数是否合规
        // 1. name、author、price 必填
        // 2. name、author 长度不能超过10个字
        // 3. name 不能重复
        checkBookAddParams(book);
        checkDuplicateName(book);
        mapper.insert(book);
    }

    //修改价格
    public void updateBase(String name, Double price) {
        Book book = mapper.getByName(name);
        book.setPrice(price);
        mapper.updateBase(book);
    }

    //根据name修改库存
    public void updateStock(String name,int stock){
        Book book=mapper.getByName(name);
        book.setStock(stock);
        mapper.updateStock(book);
    }

    public Book getByBookId(Integer id){
        Book book=mapper.getById(id);
        return book;
    }



    //删除数据
    public void delete(String name) {
        mapper.delete(name);
    }

    private void checkDuplicateName(Book book)  {
        Book dbbook = mapper.getByName(book.getName());
        if (dbbook != null) {
            throw new ServiceException("书名不能重复");
        }
    }

    private void checkBookAddParams(Book book) {

        AssertUtils.notBlank(book.getName(), "书名必填");
        AssertUtils.notBlank(book.getAuthor(), "作者名必填");
        AssertUtils.notNull(book.getPrice(), "价格必填");

        AssertUtils.gt(book.getName(), 10, "书名少于10个字");
        AssertUtils.gt(book.getAuthor(), 10, "作者名少于10个字");

    }

}
